################################################################################
# File: user.py
# Package: itacqos.uddi.views
# Author: Vincent Pretre
# Last update: $LastChangedDate: 2009-02-28 16:25:51 +0000 (Sat, 28 Feb 2009) $
################################################################################

## @package itacqos.uddi.views.user
#
# This module contains all views linked to user: login, logout, signup

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User

from uddi.models import Vendor

from common import newRender

## View used when user signs in (or logs in, as you want)
def signin(request):
	if request.method == 'POST':
		user = authenticate(username=request.POST['login'],  password=request.POST['password'])
	
		if user is not None:
			if user.is_active:
				login(request, user)
				return newRender('loginOK.html', {}, request)
			else:
				return newRender('disabledAccount.html', {}, request)
		else:
			return newRender('loginFailed.html', {}, request)
	else:
		return newRender('login.html', {}, request)

## View used when user signs out (or logs out)
def signout(request):
    logout(request)
    return newRender('logout.html', {}, request)

## View used when user signs up (or registers)
#
# If user checked the box "Are you a web service vendor", a new vendor is created.\n
# This function also authenticate the user
def signup(request):
	if request.method == 'POST':
		form = RegisterForm(request.POST)
		if form.validate():
			User.objects.create_user(form.cleaned_data['username'],	form.cleaned_data['email'], form.cleaned_data['password'])

			user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
			login(request, user)

			if form.cleaned_data['isVendor']:
				v = Vendor(name = user.username, user = user)
				v.save()

			return newRender('registerOK.html', {}, request)
		else:	
			return newRender('register.html',  {'form': form},  request)
	else:
		form = RegisterForm()
		return newRender('register.html',  {'form': form}, request)
